//定义高德地图
var map;
var curVehicleParkingInfo=[];
var curVehicleParkingMaker=new HashMap();

//定义对象
var vehicleParking = {
		/**
	     * 初始化
	     * */
		init : function(){
			  this.sliderH(); 
			  
			  //创建表头
			  this.tableTdW = [7,10,10,19,19,19,16];
			  this.tableW = global.creatTableH({
				  width:$('#tableDiv').width(),
				  widthType : '%',
				  id : '#vehicleParkingTable',
				  hTh : ['序号','车牌号','自编号','企业名称','开始停车时间','结束停车时间','停车时长'],
				  tdW : vehicleParking.tableTdW
			  });
			  this.initVehicleList();
			  this.initMyMap();
//			  this.initTable();
			  this.doSelTime();
			  this.bind();
			  this.bindExportExcel();
			  this.winH ="";
			  //this.sliderH = "";
			  this.mapH ="";
			  this.queryVehicleParking();
		},
		 /**
	     * 计算各div高度的高度
	     * */
	    sliderH : function(){
	    	var _this=this;
	    	_this.winH = $(window).height();
	    	_this.sliderh = _this.winH - 76;
	    	_this.mapH = _this.sliderh-46;
	        $('#mymap').height(_this.mapH);
	        $('#tableDiv').height(_this.mapH);
//	        $('#vehicleParkingList').height(mapH);
	    },
	    /**
	     * 初始化车辆列表
	     * */
	    initVehicleList:function(){
	    	$.ajax({
	    		type : 'post',
	    		async : false,
	    		url : appCtx + "/system/vehicle/loadUserVehicle.html",
	    		cache : false,
	    		dataType : "JSON",
	    		success : function(data) {			
	    			if(data){
	    				var selectStr="";
	    				selectStr+="<option value=''>请选择</option>";
	    				$.each(data.vehicleList,function(entryIndex,entry) {
	    					selectStr+="<option value='"+entry.vehicleId+"'>"+entry.registrationNO+"</option>";
	    				});
	    				
	    				$('#selectVehicleSel').html(selectStr);
	    				
	    				$("#selectVehicleSel").select2();

	    			}
	    		}
	    	});
	    },
	    /**
	     * 初始化地图
	     * */
	    initMyMap:function(){
	    	    map = new AMap.Map('mymap', {
	    	    resizeEnable: true,
	    	    zoom:11,
	    	    center: [116.397428, 39.90923]
	    	});
	    },
	    /**
	     * 初始化时间
	     * */
	    doSelTime:function(){
	        var startTime=$("#inputStartDate").val();
	        var endTime=$("#inputEndDate").val();
	        
	        if((startTime==null||startTime=="")&&(endTime==null||endTime=="")){
	        	var todayDate = new Date();
	        	todayDate = new Date(todayDate-86400000);
	        	var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
	        	$("#inputEndDate").val(todayDateStr);
	        	
	        	var beforeDate = new Date(todayDate-86400000*3); //当前时间向前推7天
	          var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	          if (mm.length == 1) {
	               mm = '0' + mm;
	          }
	          if (dd.length == 1) {
	               dd = '0' + dd;
	          }
	        	$("#inputStartDate").val(todayDateStr)
	        }
	      },
	      /**
		     * 初始化表格
		     * */
	      initTable:function(){
	    	  var _this=this;
	    	  /**
	  	     * 格式化时间
	  	     * */
	    	  var getFromatTime = function (duration){
	    		  var d=Math.floor(duration/(60*60*24)); 
	        	  var h=Math.floor((duration%(60*60*24))/(60*60)%24); 
	    		  var m=Math.floor((duration%(60*60))/60%60); 
	    		  var s=Math.floor((duration%(60))%60);
	    		  var sth=h+"小时";
	    		  var stm="";
	    		  var sts="";
	    			if(m<10){
	    				stm = "0"+m + "分"; 
	    			}else{
	    				stm = m + "分"; 
	    			}
	    			if(s<10){
	    				sts = "0"+s + "秒";
	    			}else{
	    				sts = s + "秒";
	    			}
	    			rsstr="";
	    			if(d>0){
	    				rsstr=d+"天"+sth+stm+sts;
	    			}else{
	    				rsstr=sth+stm+sts;
	    			}
	    			
	            return rsstr;
	          };
	          
	          /**
	  	     * 地址解析
	  	     * */
	          var getAddress = function (start_lon,start_lat,duration,registrationNO,id){
	    			
	    			showAddress(id,start_lon,start_lat);
	    			return '<div id="span'+id+'"><a href="#" >加载中..</a></div>';
	          };
	          
	          
	    	$("#vehicleParkingList").flexigrid({
	            dataType : 'json',
	            colModel : [{
	            	display : '序号',
	                name : 'id',
	                width : 5,
	                sortable : true,
	                align : 'center'
	            },{
	                display : '车牌号',
	                name : 'registrationNO',
	                width : 10,
	                sortable : false,
	                align : 'center'
	            },{
	                display : '自编号',
	                name : 'internal_number',
	                width : 8,
	                sortable : false,
	                align : 'center'
	            },{
	                display : '企业名称',
	                name : 'workUnitName',
	                width : 11,
	                sortable : false,
	                align : 'left',
	                showTitle : 'workUnitName'
	            },{
	                display : '开始停车时间',
	                name : 'start_time',
	                width : 17,
	                sortable : false,
	                align : 'left'    
	            },{
	                display : '结束停车时间',
	                name : 'end_time',
	                width : 17,
	                sortable : false,
	                align : 'left'    
	            },{
	                display : '停车时长',
	                name : 'duration',
	                width : 14,
	                sortable : false,
	                align : 'left', 
	                paramcolnames:["duration"],
	                handlefunction:getFromatTime    
	            },{
	                display : '停车位置',
	                name : 'start_lat',
	                width : 18,
	                sortable : false,
	                align : 'left',
	                paramcolnames:["start_lon","start_lat","duration","registrationNO","id"],
	                handlefunction:getAddress
	            }],
	            resizable : false,
	            sortname : "id",// 第一次加载数据时排序列
	            sortorder : "asc",// 第一次加载数据时排序类型
	            usepager : false,// 是否分页，默认为true。
	            showToggleBtn : false,
	            showTableToggleBtn : false,// 是否显示收起/打开按钮,默认不显示。
	            useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
				rp : 50,// 每页记录数，默认为10
	            rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
	            width : $('#tableDiv').width(),// 表格宽度
	            widthType: '%',
	            height :_this.mapH-60,
	            onSuccess : function(data){
	            	map.clearMap(); 
	            	for(var i=0;i<data.rows.length;i++){
	            	  var start_lon=data.rows[i].start_lon;
	            	  var start_lat=data.rows[i].start_lat;
	            	  var duration=data.rows[i].duration;
	            	  var registrationNO=data.rows[i].registrationNO;
	            	  var id=data.rows[i].id;
	            	  var marker;
	  	        	  marker = new AMap.Marker({
	  	                  icon: appCtx + "resources/images/mapTool/carYellow1.png",
	  	                  offset: new AMap.Pixel(-15, -10),
	  	                  position: [start_lon, start_lat]
	  	              });
	  	        	  marker.setMap(map);
	  	        	  var d=Math.floor(duration/(60*60*24)); 
	  	        	  var h=Math.floor((duration%(60*60*24))/(60*60)%24); 
	  	    		  var m=Math.floor((duration%(60*60))/60%60); 
	  	    		  var s=Math.floor((duration%(60))%60);
	  	    		  var sth=h+"小时";
	  	    		  var stm="";
	  	    		  var sts="";
	  	    			if(m<10){
	  	    				stm = "0"+m + "分"; 
	  	    			}else{
	  	    				stm = m + "分"; 
	  	    			}
	  	    			if(s<10){
	  	    				sts = "0"+s + "秒";
	  	    			}else{
	  	    				sts = s + "秒";
	  	    			}
	  	    			rsstr="";
	  	    			if(d>0){
	  	    				rsstr=d+"天"+sth+stm+sts;
	  	    			}else{
	  	    				rsstr=sth+stm+sts;
	  	    			}
	  	    			marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
	  	        	        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
	  	        	        content: registrationNO+"<br/>"+rsstr
	  	        	    });
	            	}
	            },
	            onSelectRow : function(row){
	            //	map.clearMap(); 
	            /*	  var start_lon=row.start_lon;
	            	  var start_lat=row.start_lat;
	            	  var duration=row.duration;
	            	  var registrationNO=row.registrationNO;
	            	  var id=row.id;
	            	  var marker;
	  	        	  marker = new AMap.Marker({
	  	                  icon: appCtx + "resources/images/mapTool/car1.png",
	  	                  offset: new AMap.Pixel(-15, -10),
	  	                  position: [start_lon, start_lat]
	  	              });
	  	        	  marker.setMap(map);
	  	        	  var d=Math.floor(duration/(60*60*24)); 
	  	        	  var h=Math.floor((duration%(60*60*24))/(60*60)%24); 
	  	    		  var m=Math.floor((duration%(60*60))/60%60); 
	  	    		  var s=Math.floor((duration%(60))%60);
	  	    		  var sth=h+"小时";
	  	    		  var stm="";
	  	    		  var sts="";
	  	    			if(m<10){
	  	    				stm = "0"+m + "分"; 
	  	    			}else{
	  	    				stm = m + "分"; 
	  	    			}
	  	    			if(s<10){
	  	    				sts = "0"+s + "秒";
	  	    			}else{
	  	    				sts = s + "秒";
	  	    			}
	  	    			rsstr="";
	  	    			if(d>0){
	  	    				rsstr=d+"天"+sth+stm+sts;
	  	    			}else{
	  	    				rsstr=sth+stm+sts;
	  	    			}
	  	    			marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
	  	        	        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
	  	        	        content: registrationNO+"<br/>"+rsstr
	  	        	    });*/
	            	map.setCenter(new AMap.LngLat(row.start_lon, row.start_lat));
	            },
	            onSelectAllRow : function(data){

	            }
	        });
	    },
	    /**
	     * 查询车辆停车分析
	     * */
	    queryVehicleParking:function(){
	    	var startTime=$("#inputStartDate").val()+" 00:00:00";
	     	var endTime=$("#inputEndDate").val()+" 23:59:59";
	     	
	     	
	     	var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
	    	var end_date = new Date(end_str);//将字符串转化为时间  
	    	//开始时间  
	    	var sta_str = (startTime).replace(/-/g,"/");  
	    	var sta_date = new Date(sta_str); 
	    	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
	    	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
	    	if(days>30){
	    		global.ajaxLoading.pop("查询时间不能超过30天",false,2000);
	    		return;
	    	}
	    	
	    	
	    	global.ajaxLoading.pop('正在拼命加载,请稍候!',true);
	    	var _this=this;
	    	map.clearMap(); 
	    	$("#vehicleParkingTable tr:not(:first)").remove();
	    	curVehicleParkingInfo=[];
	    	curVehicleParkingMaker=new HashMap();	
	        var tableW = this.tableW.width;
	    	
	    	var paramsGrid = [{
	            name : 'vehicleID',
	            value : $("#selectVehicleSel").val()
	     	},{
	            name : 'startTime',
	            value : $("#inputStartDate").val()+" 00:00:00"
	     	},{
	            name : 'timeSplit',
	            value : $("#timeSplitSel").val()
	     	},{
	            name : 'timeCount',
	            value : $("#timeCountSel").val()
	     	},{
	            name : 'endTime',
	            value : $("#inputEndDate").val()+" 23:59:59"
	     	}];
	    
	    	
	    	$.ajax({
				type : 'post',
				async : true,
				data :paramsGrid,
				url :  appCtx + "/report/VehicleParking/queryVehicleParkingListTable.html",
				cache : false,
				dataType : "json",
				success : function(data) {
					 if(data!=null && data.length>0){
						 curVehicleParkingInfo=data;
						 var tableStr="";
						 console.time('时间');
						 if(data[0].start_lon>0&&data[0].start_lat>0){
							 map.setCenter(new AMap.LngLat(data[0].start_lon, data[0].start_lat));
						 }
						 
						 for(var i=0;i<data.length;i++){
							 var _class="wu";
							 if (i%2==0){ _class="tableRow"}
							 var rsstr = getFromatTime(data[i].duration);
							 tableStr+="<tr id='tr_"+data[i].id+"' class='info_tr "+_class+"' onclick='setCenterVehicleParkingInfo(\""+ data[i].start_lon+"\",\""+data[i].start_lat+"\",\""+data[i].id+"\",\""+data[i].registrationNO+"\",\""+rsstr+"\")'>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[0]+"px' title="+data[i].id+">"+(data[i].id)+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[1]+"px' title="+data[i].registrationNO+">"+data[i].registrationNO+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[2]+"px' title="+data[i].internal_number+">"+data[i].internal_number+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[3]+"px' title="+data[i].workUnitName+">"+data[i].workUnitName+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[4]+"px' title="+data[i].start_time+">"+data[i].start_time+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[5]+"px' title="+data[i].end_time+">"+data[i].end_time+"</div></td>" +
							 		"<td><div class='textOverFlow' style='width:"+tableW[6]+"px' title="+rsstr+">"+rsstr+"</div></td>" +
							 	"</tr>";
			            	  var start_lon=data[i].start_lon;
			            	  var start_lat=data[i].start_lat;
			            	  var duration=data[i].duration;
			            	  var registrationNO=data[i].registrationNO;
			            	  var id=data[i].id;
			            	  var marker;
			  	        	  marker = new AMap.Marker({
			  	                  icon: appCtx+"resources/images/mapTool/home_icon_location.png",
			  	                  offset: new AMap.Pixel(-15, -10),
			  	                  position: [start_lon, start_lat]
			  	              });
			  	        	  marker.setMap(map);
			  	    			var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -5)});
			          			marker.content = '<div style="display:none;">'+id+','+start_lon+','+start_lat+'</div><div style="width:300px;">车牌号：'+registrationNO+'</br>停车时长：'+rsstr+'</br>停车位置：<span id="span'+id+'"></span></div> ';
			          			
			          			marker.on('click', function(e){
			          				 //var strtemp=e.target.content.substring(26).split("<")[0].split(",");
			          				 var content = e.target.content;
			          				 var strtemp = content.substring(content.indexOf('>')+1,content.indexOf('</div>')).split(',');
//			          				 e.target.content=e.target.content+'</br>停车位置：<span id="span'+strtemp[0]+'"></span> ';
			          				 infoWindow.setContent(e.target.content);
			          			     infoWindow.open(map, e.target.getPosition());	
			          			     showAddress(strtemp[0],strtemp[1],strtemp[2]);
			          			});
			          			curVehicleParkingMaker.put(id,infoWindow);
						 }
						 $("#vehicleParkingTable").append(tableStr);
						 global.ajaxLoading.close();
						 console.timeEnd('时间');
					 }else{
						 global.ajaxLoading.pop('无数据存在',false,2000);
						 
					 }
				}
			});
	    	
	    	
	    },
	    /**
	     * 获取列
	     * */
	    getColumn:function(){
	    	return [{
            	display : '序号',
                name : 'id',
                width : 50,
                sortable : true,
                align : 'center'
            },{
                display : '车牌号',
                name : 'registrationNO',
                width : 120,
                sortable : false,
                align : 'center'
            },{
                display : '自编号',
                name : 'internal_number',
                width : 120,
                sortable : false,
                align : 'center'
            },{
                display : '企业名称',
                name : 'workUnitName',
                width : 180,
                sortable : false,
                align : 'center'
            },{
                display : '开始停车时间',
                name : 'start_time',
                width : 150,
                sortable : false,
                align : 'left'    
            },{
                display : '结束停车时间',
                name : 'end_time',
                width : 150,
                sortable : false,
                align : 'left'    
            },{
                display : '停车时长',
                name : 'duration',
                width : 150,
                sortable : false,
                align : 'left'   
            }];
	    },
	    /**
	     * 导出
	     * */
	    exportExcel : function(){
	    	
	    	var answer = confirm("确定导出车辆停车分析导出?");
	        if(!answer){
	        	return false;
	        }
	        
			var header1 = JSON.stringify(vehicleParking.getColumn());

			 
			//表头
			var colModelList=new Array();
			colModelList.push(header1);
			var colModel= $.toJSON(colModelList);
			

				
			var paramsGrid =  {
					vehicleID:$("#selectVehicleSel").val(),
					startTime:$("#inputStartDate").val()+" 00:00:00",
					timeSplit:$("#timeSplitSel").val(),
					timeCount:$("#timeCountSel").val(),
					endTime:$("#inputEndDate").val()+" 23:59:59",
					colModel:colModel,
					title:"车辆停车分析导出",
					imgsrc:null
			};
			
			
	
			
			post(appCtx+"report/VehicleParking/exportVehicleParking.html",paramsGrid);
			
		},
		bindExportExcel:function(){
			var _this=this;
	    	$(".query-export").click(function(){
	    		_this.exportExcel();
	    	});
		},
	    bind:function(){
	    	var _this=this;
	    	$(".query-require").click(function(){
	    		_this.queryVehicleParking();
	    	});
	    	
	    	$('#showMap').click(function(){
	    		if($(this).hasClass('active')){
	    			$(this).removeClass('active');
	    			$('#tableDiv').show();
	    			$('#mapWarp').css({
	    				width:'40%',
	    				'padding-left':10
	    			});
	    		}else{
	    			$(this).addClass('active');
	    			$('#tableDiv').hide();
	    			$('#mapWarp').css({
	    				width:'100%',
	    				'padding-left':0
	    			});
	    		}
	    	});
	    } 
}
/**
 * 初始化
 * */
vehicleParking.init();

function showAddress(id,start_lon,start_lat){
	var ctrl="#span"+id;
	var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
    });        
    geocoder.getAddress(new AMap.LngLat(start_lon,start_lat), function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
        	var address=result.regeocode.formattedAddress;
        	$(ctrl).html(address);
        	//$(ctrl).attr("title",address);
        }
    });    
}

function setCenterVehicleParkingInfo(start_lon,start_lat,id,registrationNO,rsstr){
	$(".info_tr").removeClass("tableTr");
	$("#tr_"+id).addClass("tableTr");
	var content = '<div style="display:none">'+id+','+start_lon+','+start_lat+'</div><div style="width:300px;">车牌号：'+registrationNO+'</br>停车时长：'+rsstr+'</br>停车位置：<span id="span'+id+'"></span></div> ';	
	map.setCenter(new AMap.LngLat(start_lon,start_lat));
	curVehicleParkingMaker.get(id).setContent(content);
	curVehicleParkingMaker.get(id).open(map,[start_lon, start_lat]);
	showAddress(id,start_lon,start_lat);
}

/**
   * 格式化时间
   * */
function getFromatTime(duration){
	  var d=Math.floor(duration/(60*60*24)); 
	  var h=Math.floor((duration%(60*60*24))/(60*60)%24); 
	  var m=Math.floor((duration%(60*60))/60%60); 
	  var s=Math.floor((duration%(60))%60);
	  var sth=h+"小时";
	  var stm="";
	  var sts="";
		if(m<10){
			stm = "0"+m + "分"; 
		}else{
			stm = m + "分"; 
		}
		if(s<10){
			sts = "0"+s + "秒";
		}else{
			sts = s + "秒";
		}
		rsstr="";
		if(d>0){
			rsstr=d+"天"+sth+stm+sts;
		}else{
			rsstr=sth+stm+sts;
		}
		
    return rsstr;
  };
  
  /**
   * 地址解析
   * */
  function getAddress(start_lon,start_lat,duration,registrationNO,id){
	  /*onclick="showAddress("'+id+'","'+start_lon+'","'+start_lat+'")"*/
		//showAddress(id,start_lon,start_lat);
		return '<div id="span'+id+'"><a href="javascript:;" onclick="showAddress(\''+id+'\',\''+start_lon+'\',\''+start_lat+'\')" >查看地址</a></div>';
  };